<template>
    <section style="background-color: white;display: flex;flex-direction: column;">

        <el-form :model="queryParams" inline>

            <el-form-item>
                <el-date-picker v-model="queryParams.dateRange" type="datetimerange"
                    :default-time="['00:00:00', '23:59:59']" range-separator="至" start-placeholder="开始日期"
                    end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss" />
            </el-form-item>

            <el-form-item label="类型" prop="type">
                <el-select v-model="queryParams.type" placeholder="请选择">
                    <el-option label="城市" value='1'></el-option>
                    <el-option label="省份" value='0'></el-option>
                </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="small" @click="resetQuery">全部</el-button>
            </el-form-item>
        </el-form>

        <div ref="cityRef" style="background-color: white;display: flex;flex-direction: column;flex:1;height: 500px;">
            <div id="CityChart" style="min-height: 500px; flex: 1; height: 500px; width: 100%;"></div>
            <div style="display: flex;justify-content: flex-end;">
                <el-button size="max" type="text" icon="el-icon-full-screen" @click="fullDom()"></el-button>
            </div>
        </div>
    </section>
</template>


<script>
import * as echarts from 'echarts';
import { getCity } from "@/api/source/history";
import dayjs from 'dayjs';



var struct_colors = [
    '#ed6f6d', '#f3765d', '#f77a57', '#f98866', '#f99579',
    '#ff9f3b', '#f0a732', '#e6a840', '#e9b253', '#ebbb66',
    '#78b7e8', '#59b1f3', '#66bbf5', '#6ec3f2', '#75cae2',
    '#70cccc', '#5dc4c4', '#4dbebd', '#4cc1a7', '#4fca96',
    '#4cc686'
];
var RICH = {
    name: {
        color: '#fff',
        fontSize: 24
    },
    basic: {
        color: '#fff',
        fontSize: 18,
        lineHeight: 16

    }
};
var structs_datas = [];


function format_struct_data(children, structs_datas) {
    // 添加每个单位的颜色
    for (var prop in children) {
        var index = Math.floor(Math.random() * 20);
        var value = 1;
        if (children[prop].value !== 0) {
            value = children[prop].value;
        }
        var tmp = {
            itemStyle: {
                normal: {
                    color: struct_colors[index]
                }
            },
            name: children[prop].name,
            children: [],
            value: children[prop].value
        }
        format_struct_data(children[prop].children, tmp.children);
        if (tmp.children.length === 0) {
            delete tmp.children;
        }
        structs_datas.push(tmp);
        // return structs_datas;

    }

}

export default {
    name: 'City',
    data() {
        return {
            queryParams: {
                startCreateTime: null,
                endCreateTime: null,
                type: '1',
                dateRange: [`${dayjs().format('YYYY-MM-DD')} 00:00:00`, `${dayjs().format('YYYY-MM-DD')} 23:59:59`],// 获取日期部分并转成字符串
            },
            myChart: null,
            CityData: null,
        }
    },
    mounted() {
        this.rederData();
    },
    methods: {
        async fullDom() {
            const elem = this.$refs.cityRef;
            if (!document.fullscreenElement) {
                // 如果当前不是全屏状态，则进入全屏
                if (elem.requestFullscreen) {
                    await elem.requestFullscreen();
                } else if (elem.webkitRequestFullscreen) {
                    await elem.webkitRequestFullscreen();
                } else if (elem.msRequestFullscreen) {
                    await elem.msRequestFullscreen();
                }
                const f = (event) => {
                    if (document.fullscreenElement === null) {
                        this.myChart.resize()
                        elem.removeEventListener(fullscreenchange, f)
                    }
                }
                elem.addEventListener('fullscreenchange', f);
            } else {
                // 如果当前是全屏状态，则退出全屏
                if (document.exitFullscreen) {
                    await document.exitFullscreen();
                } else if (document.webkitExitFullscreen) {
                    await document.webkitExitFullscreen();
                } else if (document.msExitFullscreen) {
                    await document.msExitFullscreen();
                }
            }
            setTimeout(() => {
                console.log(this.myChart.resize, document.querySelector('#CityChart').getBoundingClientRect())
                this.myChart.resize()
            })
        },

        rederData() {
            const sata = { ...this.queryParams }
            if (sata.dateRange && sata.dateRange.length === 2) {
                const startDate = this.queryParams.dateRange[0];
                const endDate = this.queryParams.dateRange[1];
                sata.startCreateTime = startDate;
                sata.endCreateTime = endDate;
            }
            delete sata.dateRange
            getCity(sata).then(response => {
                const CityData = response.data.cityList;
                structs_datas = [];
                format_struct_data(CityData, structs_datas);
                this.renderRealNameRateChart();
            });

        },

        handleQuery() {
            this.rederData();
        },

        /** 重置按钮操作 */
        resetQuery() {
            this.queryParams.dateRange = [];
            this.rederData()
        },

        // handleDateChange() {
        //     this.rederData({ dateInfo: this.queryParams.dateInfo });

        // },
        // handleClear() {
        //     this.queryParams.dateInfo = null;  
        // },
        renderRealNameRateChart() {
            if (!this.myChart) {
                this.myChart = echarts.init(document.getElementById('CityChart')); // 初始化ECharts实例
            }
            console.log(this.queryParams.type === '1' ? '城市' : '省份', this.queryParams.type)
            this.myChart.setOption({
                title: {
                    left: 'leafDepth'
                },
                tooltip: {
                    formatter: function (info) {
                        var val = info.data.value;
                        var name = info.name;
                        return [
                            '<h4>' + name + '</>',
                            '<div style="font-size: 36px;">' + val + '</>',
                        ].join('\n');
                    },
                },
                series: [{
                    name: this.queryParams.type === '1' ? '城市' : '省份',
                    type: 'treemap',
                    visibleMin: 1,
                    data: structs_datas,
                    leafDepth: 1,
                    label: {
                        normal: {
                            show: true,
                            position: 'insideTopLeft',
                            formatter: function (a) {
                                return '{Name|' + a.name + '}' + "\n\n" + "{basic| " + a.data.value + '}';
                            },
                            textStyle: {
                                fontSize: '18',
                                fontWeight: 'bold'
                            },
                            rich: RICH,
                        },
                    },
                    levels: [{
                        itemStyle: {
                            normal: {
                                borderWidth: 0,
                                gapWidth: 2
                            }
                        }
                    }, {
                        itemStyle: {
                            normal: {
                                gapWidth: 2,
                            }
                        }
                    }, {
                        itemStyle: {
                            normal: {
                                gapWidth: 2,
                            }
                        }
                    }],
                    breadcrumb: {
                        show: true,
                        // "height": 22,
                        left: "10%",
                        top: "93%",
                        emptyItemWidth: 25,
                        itemStyle: {
                            normal: {
                                color: "#fff",
                                borderColor: "rgba(255,255,255,0.7)",
                                borderWidth: 1,
                                shadowColor: "rgba(150,150,150,1)",
                                shadowBlur: 3,
                                shadowOffsetX: 0,
                                shadowOffsetY: 0,
                                textStyle: {
                                    color: "#000",
                                    fontWeight: 'bold'
                                }
                            },
                            emphasis: {
                                textStyle: {}
                            }
                        }
                    },
                }]
            });

        },
    }
}
</script>

<style lang="scss" scoped>
.smaller-form {
    font-size: smaller;
}
</style>